package com.nixsolutions.dao;

import com.nixsolutions.bean.User;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author yakimovich
 */
@Repository
public class HibernateUserDao implements UserDao {

    @Autowired
    private SessionFactory sessionFactory;

    public HibernateUserDao() {
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void create(User user) {

        getCurrentSession().save(user);
    }

    @Override
    public void update(User user) {

        getCurrentSession().update(user);
    }

    @Override
    public void remove(User user) {

        getCurrentSession().delete(user);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<User> findAll() {

        List<User> users = null;

        Criteria criteria = getCurrentSession()
                .createCriteria(User.class);
        users = criteria.list();

        return users;
    }

    @Override
    @SuppressWarnings("unchecked")
    public User findByLogin(String login) {

        User user = null;

        Criteria criteria = getCurrentSession()
                .createCriteria(User.class);
        criteria.add(Restrictions.eq("login", login));
        List<User> users = criteria.list();

        if (!users.isEmpty()) {
            user = users.get(0);
        }
        return user;
    }

    @Override
    @SuppressWarnings("unchecked")
    public User findByEmail(String email) {

        User user = null;

        Criteria criteria = getCurrentSession()
                .createCriteria(User.class);
        criteria.add(Restrictions.eq("email", email));
        List<User> users = criteria.list();
        if (!users.isEmpty()) {
            user = users.get(0);
        }
        return user;
    }
}
